<?php

define( 'DOCUMENT_ROOT', dirname( __DIR__ ) . '/' );
define( 'SERVER_ROOT', dirname( __DIR__ ) . '/server/' );

include dirname( __DIR__ ) . '/vendor/autoload.php';

$arrCfg = parseCmd( $argv );

if( $arrCfg[ 'stop' ] )
{
    stopServer();
}

server\HttpServer::getInstance( $arrCfg );


function stopServer()
{
    $swooleCfg = include DOCUMENT_ROOT . 'config/swoole.php';

    $pid = -1;

    if( isset( $swooleCfg->pid_file ) && file_exists( $swooleCfg->pid_file ))
    {
        $pid = file_get_contents( $swooleCfg->pid_file );
    }

    if( -1 != $pid )
    {
        //$pid = $arrMatches[1];

        if( posix_kill( $pid, SIGTERM ))
        {
            echo "成功向进程　$pid 发送关闭信号！", PHP_EOL;
        }
        else
        {
            echo "向进程　$pid 发送关闭信号失败！", PHP_EOL;
        }
    }
    else
    {
        echo '已停止无需再发送终止进程信号！', PHP_EOL;
    }

    exit();
}

function parseCmd( $argv )
{
    $arrCfg = [];

    $arrCfg[ 'stop' ] = false;

    foreach( $argv as $arg )
    {
        if( '-d' == $arg )
        {
            $arrCfg['daemonize'] = true;
        }
        elseif( '-D' == $arg )
        {
            $arrCfg['daemonize'] = false;
        }
        elseif( strpos( $arg, '--worker_num' ) !== false )
        {
            $arrExploded = explode( '=', $arg );

            if( count( $arrExploded ) >= 2 )
            {
                $arrCfg['worker_num'] = $arrExploded[1];
            }
        }
        elseif( strpos( $arg, 'stop' ) !== false )
        {
            $arrCfg[ 'stop' ] = true;
        }
        elseif( strpos( $arg, '-h' ) !== false )
        {
            usage();

            exit();
        }

    }

    return $arrCfg;
}

function usage()
{
    echo <<<EOT

php server.php -d               run in daemonize mode
php server.php -D               run in foreground mode
php server.php --worker_num=N   set runing http worker
php server.php stop             stop the server
php server.php -h               show help   

EOT;

}